<template>
  <div class="login">
    <div @click="loginBox()" v-if="nickname === ''">未登录</div>
    <div v-if="userPic !== ''" class="picBox">
      <img :src="userPic" alt="用户头像" />
    </div>
    <div v-if="nickname !== ''" class="nickname">{{ nickname }}</div>
    <!-- 下拉菜单 -->
    <el-dropdown v-if="userPic !== ''">
      <span class="el-dropdown-link">
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item>
          <div @click="user()">个人中心</div>
        </el-dropdown-item>
        <el-dropdown-item>
          <div @click="logout()">登出</div>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <!-- 登录弹窗区 -->
    <el-dialog title="登录" :visible.sync="dialogVisible" width="400px" :before-close="handleClose">
      <!-- 手机号登录 -->
      <!-- 账号密码表单 -->
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="demo-ruleForm">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="loginForm.phone" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" size="medium"></el-input>
        </el-form-item>
      </el-form>

      <div class="bot">
        <el-checkbox v-model="checked">记住密码</el-checkbox>
        <div @click="qrLogin()">二维码登录</div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="login()">登录</el-button>
      </span>
    </el-dialog>

    <!-- 二维码登录 -->
    <el-dialog title="二维码登录(使用手机app扫码登录)" :visible.sync="dialogVisible2" width="400px" :before-close="handleClose2">
      <div class="qrCode">
        <el-image :src="qrCode"></el-image>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['change']),
  },
  mounted() {
    if (localStorage.getItem('cookie') !== null) {
      this.cookie = localStorage.getItem('cookie');
      this.uid = localStorage.getItem('uid');
      this.getInfo()
      this.loginForm.phone = localStorage.getItem('phone');
      this.loginForm.password = localStorage.getItem('password');
      this.saveCookie({ cookie: this.cookie });
    }
  },
  watch: {
    change(newVal, oldVal) {
      this.getInfo()
    },
  },
  data() {
    return {
      loginForm: {
        phone: '',
        password: '',
      },
      // 用户头像
      userPic: '',
      // 用户名称
      nickname: '',
      // cookie
      cookie: '',
      // 表单验证规则
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            message: '长度必须为11位数字',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
        ],
      },
      dialogVisible: false,
      dialogVisible2: false,
      checked: true,
      qrCode: '',
    };
  },
  methods: {
    ...mapActions(['saveCookie', 'saveUserId']),
    loginBox() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        console.log(1111)
        this.$refs.loginFormRef.resetFields();
      });
    },
    async login() {
      this.$refs.loginFormRef.validate(async (e) => {
        if (!e) return;
        this.loginFn();
        this.dialogVisible = false;
      });
    },

    async loginFn() {
      this.$api
        .login({
          phone: this.loginForm.phone,
          password: this.loginForm.password,
          timestamp: this.$utils.timestamp(),
        })
        .then((ret) => {
          if (ret.code !== 200) {
            return this.$message.error(`登录失败,${ret.message}`);
          } else {
            this.$message({
              message: '登录成功',
              type: 'success',
            });
            if (this.checked === true) {
              localStorage.setItem('phone', this.loginForm.phone);
              localStorage.setItem('password', this.loginForm.password);
            }
            //   登录成功存入cookie
            localStorage.setItem('cookie', ret.cookie);
            //   存入用户名
            localStorage.setItem('nickname', ret.profile.nickname);
            //    存入用户ID
            localStorage.setItem('uid', ret.account.id);
            // 存入用户头像
            localStorage.setItem('avatarUrl', ret.profile.avatarUrl)
            //    存入VUEX
            this.$store.commit('saveProfile', { profile: ret.profile });
            // 往vuex中存cookie
            this.saveCookie({ cookie: ret.cookie });
            //    再去浏览器缓存中读取
            this.nickname = localStorage.getItem('nickname');
            this.cookie = localStorage.getItem('cookie');
            this.uid = localStorage.getItem('uid');
            this.userPic = localStorage.getItem('avatarUrl');
          }
        });
    },

    // 登出
    async logout() {
      this.$api.logout({ cookie: this.cookie, uid: this.uid, timestamp: this.$utils.timestamp() }).then((ret) => {
        this.$message({
          message: '退出登录',
          type: 'error',
        });
        this.userPic = '';
        this.nickname = '';
        this.cookie = '';
        localStorage.clear();
        location.reload()
      });
    },

    handleClose() {
      this.dialogVisible = false;
      this.loginForm.phone = null;
      this.loginForm.password = null;
      this.$refs.loginFormRef.resetFields();
    },

    handleClose2() {
      this.dialogVisible2 = false
    },
    user() {
      this.saveUserId({ userid: this.uid })
      this.$router.push('/userPage');
    },

    qrLogin() {
      this.dialogVisible2 = true
      this.getKey()
    },

    // 生成key
    getKey() {
      this.$api.getKey({ timestamp: this.$utils.timestamp() }).then((ret) => {
        if (ret.code === 200) {
          this.$api.createQrCode({ key: ret.data.unikey, qrimg: ret.data.unikey, timestamp: this.$utils.timestamp() }).then((res) => {
            this.qrCode = res.data.qrimg
            const timer = setInterval(() => {
              this.$api.scanQr({ key: ret.data.unikey, timestamp: this.$utils.timestamp() }).then((res_) => {
                if (res_.code === 803) {
                  this.$message({
                    message: '授权登陆成功',
                    type: 'success',
                  });
                  localStorage.setItem('cookie', res_.cookie);
                  this.cookie = localStorage.getItem('cookie');
                  this.$api.getUserInfo({ cookie: res_.cookie }).then((statusRes) => {
                    localStorage.setItem('nickname', statusRes.profile.nickname);
                    //    存入用户ID
                    localStorage.setItem('uid', statusRes.account.id);
                    this.saveCookie({ cookie: res_.cookie });
                    // 存入用户头像
                    localStorage.setItem('avatarUrl', statusRes.profile.avatarUrl)
                    this.$store.commit('saveProfile', { profile: statusRes.profile });
                    this.nickname = localStorage.getItem('nickname');
                    this.cookie = localStorage.getItem('cookie');
                    this.uid = localStorage.getItem('uid');
                    this.userPic = localStorage.getItem('avatarUrl');
                  })
                  clearInterval(timer);
                  this.dialogVisible2 = false;
                  this.dialogVisible = false;
                } else if (res_.code === 800) {
                  this.$message({
                    message: '二维码过期，需要重新获取',
                    type: 'error',
                  });
                  clearInterval(timer)
                }
              })
            }, 1000);
          })
        }
      })
    },


    // 获取用户基础信息
    getInfo() {
      localStorage.removeItem('nickname');
      localStorage.removeItem('avatarUrl');
      setTimeout(() => {
        this.$api.userItem({ uid: this.uid, cookie: this.cookie, timestamp: this.$utils.timestamp() }).then((ret) => {
          localStorage.setItem('nickname', ret.profile.nickname);
          localStorage.setItem('avatarUrl', ret.profile.avatarUrl)
          this.nickname = ret.profile.nickname;
          this.userPic = ret.profile.avatarUrl;
        })
      }, 1000);
    },
  },
};
</script>

<style scoped>
.login {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.el-button {
  width: 100%;
}

.el-form {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.picBox {
  width: 50px;
  height: 40px;
}

.picBox img {
  width: 50px;
  height: 40px;
  object-fit: contain;
}

.el-dialog {
  z-index: 3001;
}

.bot {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
}

.qrCode {
  display: flex;
  justify-content: center;
}
</style>
